/**
 * AesUtils.java
 * 
 * Create Version: 1.0
 * Author: 徐舟骏
 * Create Date: 2012-5-24
 */
package ysyh55.android.base.util;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * AesUtils AES加密工具类
 * 
 * @author 徐舟骏
 */
public class AESUtils {
	/**
	 * 解密方法
	 * 
	 * @param sSrc
	 * @param sKey
	 * @return
	 * @throws Exception
	 */
	public static String decrypt(String sSrc, String sKey) throws Exception {
		Cipher cipher = Cipher.getInstance("AES");
		cipher.init(Cipher.DECRYPT_MODE, getKey(sKey));
		byte[] encrypted1 = hex2byte(sSrc);
		byte[] original = cipher.doFinal(encrypted1);
		return new String(original);
	}

	/**
	 * 加密方法
	 * 
	 * @param sSrc
	 * @param sKey
	 * @return
	 * @throws Exception
	 */
	public static String encrypt(String sSrc, String sKey) throws Exception {
		Cipher cipher = Cipher.getInstance("AES");
		cipher.init(Cipher.ENCRYPT_MODE, getKey(sKey));
		byte[] encrypted = cipher.doFinal(sSrc.getBytes());
		return byte2hex(encrypted).toLowerCase();
	}

	private static SecretKeySpec getKey(String keyStr) throws Exception {
		StringBuffer sb = new StringBuffer(keyStr);
		StringBuffer sb2 = new StringBuffer();

		for (int i = 0; i < sb.length(); i++) {
			if (i % 2 == 0) {
				sb2.append(sb.substring(i, i + 1));
			}
		}

		byte[] raw = sb2.toString().getBytes("ASCII");
		return new SecretKeySpec(raw, "AES");
	}

	private static byte[] hex2byte(String strhex) {
		int l = strhex.length();
		byte[] b = new byte[l / 2];
		for (int i = 0; i != l / 2; i++) {
			b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2), 16);
		}
		return b;
	}

	private static String byte2hex(byte[] b) {
		String hs = "";
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1) {
				hs = hs + "0" + stmp;
			} else {
				hs = hs + stmp;
			}
		}
		return hs.toUpperCase();
	}
}
